package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
)

type User struct {
	Id       int    `orm:"auto;pk"`
	Account  string `orm:"size(32)" json:"account"`
	Password string `orm:"size(100)" json:"password"`
}

// GetUserByUsername 根据手机号码获取到用户信息
func GetUserByUsername(account string) (*User, error) {
	var user User
	err := orm.NewOrm().QueryTable("user").Filter("account", account).One(&user)
	if err != nil {
		if err == orm.ErrNoRows {
			return nil, nil
		}
		return nil, err
	}
	return &user, nil
}

// GetUserByUsername 根据Id获取到用户信息
func GetUserByID(id int64) (*User, error) {
	var user User
	err := orm.NewOrm().QueryTable("user").Filter("id", id).One(&user)
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// CreateUser 创建用户
func CreateUser(info *User) (*User, error) {
	o := orm.NewOrm()
	// 保存用户到数据库
	id, err := o.Insert(info)
	fmt.Println(id, err)
	if err != nil {
		return nil, err
	}
	return GetUserByID(id)
}
